/**
 * @description: 全屏相关的工具函数
 */
import { ref, onMounted, onUnmounted } from 'vue';

export const useFullscreen = () => {
    const isFullscreen = ref(false);

    // 检查当前全屏状态
    const checkFullscreenStatus = () => {
        isFullscreen.value = !!(
            document.fullscreenElement ||
            (document as any).webkitFullscreenElement ||
            (document as any).msFullscreenElement
        );
    };

    // 处理全屏变化
    const handleFullscreenChange = () => {
        checkFullscreenStatus();
    };

    // 进入全屏
    const enterFullscreen = async (element: Element = document.documentElement) => {
        try {
            if (element.requestFullscreen) {
                await element.requestFullscreen();
            } else if ((element as any).webkitRequestFullscreen) {
                await (element as any).webkitRequestFullscreen();
            } else if ((element as any).msRequestFullscreen) {
                await (element as any).msRequestFullscreen();
            }
        } catch (error) {
            console.error('进入全屏失败:', error);
            throw error;
        }
    };

    // 退出全屏
    const exitFullscreen = async () => {
        try {
            if (document.exitFullscreen) {
                await document.exitFullscreen();
            } else if ((document as any).webkitExitFullscreen) {
                await (document as any).webkitExitFullscreen();
            } else if ((document as any).msExitFullscreen) {
                await (document as any).msExitFullscreen();
            }
        } catch (error) {
            console.error('退出全屏失败:', error);
            throw error;
        }
    };

    // 切换全屏
    const toggleFullscreen = async (element?: Element) => {
        if (isFullscreen.value) {
            await exitFullscreen();
        } else {
            await enterFullscreen(element);
        }
    };

    onMounted(() => {
        // 添加事件监听
        document.addEventListener('fullscreenchange', handleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.addEventListener('msfullscreenchange', handleFullscreenChange);

        // 初始化状态
        checkFullscreenStatus();
    });

    onUnmounted(() => {
        // 移除事件监听
        document.removeEventListener('fullscreenchange', handleFullscreenChange);
        document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.removeEventListener('msfullscreenchange', handleFullscreenChange);
    });

    return {
        isFullscreen,
        enterFullscreen,
        exitFullscreen,
        toggleFullscreen
    };
}